package com.wiloon.java8x.zip;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class ZipUtil {
	private static Logger logger = LoggerFactory.getLogger(ZipUtil.class);
	private static String encoding = "ISO-8859-1";


	public static String compress(String str) throws IOException {
		logger.debug("compress=" + str);
		logger.debug("in str=" + str);
		if (str == null || str.length() == 0) {
			return str;
		}
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		GZIPOutputStream gzip = new GZIPOutputStream(out);
		gzip.write(str.getBytes());
		gzip.close();
		String outStr = out.toString(encoding);
		logger.debug("out Str=" + outStr);
		return outStr;
	}

	public static String uncompress(String str) throws IOException {
		logger.debug("uncompress=" + str);
		logger.debug("in str=" + str);
		if (str == null || str.length() == 0) {
			return str;
		}
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		ByteArrayInputStream in = new ByteArrayInputStream(
				str.getBytes(encoding));
		GZIPInputStream gunzip = new GZIPInputStream(in);
		byte[] buffer = new byte[256];
		int n;
		while ((n = gunzip.read(buffer)) >= 0) {
			out.write(buffer, 0, n);
		}

		String outStr = out.toString();
		logger.debug("out Str=" + outStr);
		return outStr;
	}


	public static void main(String[] args) throws IOException {
		System.out.println(ZipUtil.uncompress(ZipUtil.compress("China")));
	}

}